#define _CRT_SECURE_NO_WARNINGS 1

#include "heap.h"

void HPInit(HP* hp)
{
	assert(hp);

	hp->a = NULL;
	hp->size = hp->capacity = 0;
}

void HPInitArr(HP* hp, HPDataType* a, int n)
{
	hp->a = (HPDataType*)malloc(sizeof(int) * n);
	if (hp->a == NULL)
	{
		perror("malloc fail");
		return;
	}
	memcpy(hp->a, a, sizeof(int) * n);
	hp->size = hp->capacity = n;
	for (int i = (hp->size-1-1)/2; i < hp->size; i++)
	{
		AdjustDown(hp->a, hp->size, i);
	}
}

void HPDestory(HP* hp)
{
	assert(hp);

	free(hp->a);
	hp->a = NULL;
	hp->size = hp->capacity = 0;
}

void Swap(int* px,int* py)
{
	int tmp = *px;
	*px = *py;
	*py = tmp;
}

void AdjustUp(HPDataType* a, int n, int child)
{
	int parent = (child - 1) / 2;

	while (child > 0)
	{
		if (a[parent] < a[child])
		{
			Swap(&a[parent], &a[child]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void HPPush(HP* hp, HPDataType x)
{
	assert(hp);

	if (hp->size == hp->capacity)
	{
		int newCapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
		HPDataType* tmp = (HPDataType*)realloc(hp->a,sizeof(HPDataType) * newCapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		hp->a = tmp;
		hp->capacity = newCapacity;
	}

	hp->a[hp->size] = x;
	hp->size++;

	AdjustUp(hp->a, hp->size, hp->size - 1);
}

void AdjustDown(HPDataType* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (a[child] < a[child + 1] && child + 1< n)
		{
			child++;
		}
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void HPPop(HP* hp)
{
	assert(hp);
	assert(!HPEmpty(hp));

	Swap(&hp->a[0], &hp->a[hp->size - 1]);
	hp->size--;
	AdjustDown(hp->a, hp->size, 0);


}

HPDataType HPTop(HP* hp)
{
	assert(hp);
	assert(!(HPEmpty(hp)));

	return hp->a[0];
}

int HPSize(HP* hp)
{
	assert(hp);

	return hp->size;
}

bool HPEmpty(HP* hp)
{
	assert(hp);

	return hp->size == 0;
}

void HeapSort(int* a, int n)
{
	assert(a);

	for (int i = (n - 1 - 1) / 2; i >= 0; i--)
	{
		AdjustDown(a, n, i);
	}

	int end = n - 1;
	while (end > 0)
	{
		Swap(&a[0], &a[end]);
		AdjustDown(a, end, 0);
		end--;
	}
}
